#include <vector>
#include "GetTime.h"
#include "RakSleep.h"
#include "functions.h"
#include "player.h"
#include "npc.h"
#include "tile.h"
#include "constants.h"
#include "globals.h"
#include "timer.h"

#define FPS 60

#define MYSQL_DB "urpg"
#define MYSQL_SERVER "192.168.1.4"
#define MYSQL_USER "root"
#define MYSQL_PASS "humppaasuomesta"

bool loop = true;

int main(int argc, char* args[])
{
    unsigned int frame = 0;
    double dt = 1000 / FPS;
    double frameTime = 0;
    Timer delta;

    output.write("Initializing ...");

    if (!db.connect(MYSQL_DB, MYSQL_SERVER, MYSQL_USER, MYSQL_PASS))
    {
        output.write("Failed connecting to MySQL server!");
        return 1;
    }
    output.write("Connected to MySQL server on %s", MYSQL_SERVER);

    /*account a = db.get_account(1);
    output.write("1: %s %s %i", a.username.c_str(), a.pass_hash.c_str(), a.admin);

    std::vector<character> chars = db.get_characters(2);
    for (int i = 0; i < chars.size(); i++) {
        output.write("%i: %s", i, chars[i].name.c_str());
    }*/

    //Set the tiles
    if(set_tiles(tiles, "001.map") == false)
    {
        output.write("Failed setting tiles!");
        return 1;
    }

    for (int i = 0; i < 32; i++) {
        new Npc(i + 1, "KARI", 256, 256);
    }

    double currentTime = RakNet::GetTimeMS();
    double startTime = currentTime;

	while (loop)
	{
        if (frameTime < dt)
        {
            RakSleep(dt - frameTime);
        }

        double newTime = RakNet::GetTimeMS();
        double frameTime = newTime - currentTime;
        currentTime = newTime;

	    net.receive_data();
        std::map<RakNet::RakNetGUID, Player*> Players = Player::GetPlayerList();
        std::map<int, Npc*> Npcs = Npc::GetNpcList();

        for (std::map<int, Npc*>::iterator i = Npcs.begin(); i != Npcs.end(); i++)
        {
            Npc* npc = i->second;
            npc->work(delta.get_ticks());
        }

        for (std::map<RakNet::RakNetGUID, Player*>::iterator i = Players.begin(); i != Players.end(); i++)
        {
            Player* player = i->second;
            player->move(delta.get_ticks());
        }

        for (std::map<int, Npc*>::iterator i = Npcs.begin(); i != Npcs.end(); i++)
        {
            Npc* npc = i->second;
            npc->move(delta.get_ticks());
        }

        delta.start();

        frame++;
	}

    output.write("Cleaning up ...");

	net.shutdown();
	output.close();

    return 0;
}
